<template>
  <div class="appoint-page">
    <GhNavBar title="预约-管理" />
   <!-- 头部搜索和添加咨询师空闲时间 -->
   <div class="head">
    <van-search class="search"  v-model="value" placeholder="搜索标题"   />
    <van-button class="add-btn" @click="addBookilng_time" native-type="submit"  block  >
           创建预约
     </van-button>
    </div>
    <div class="top-box" @click="router.push('/setTimeSlots')">
      <div class="top_lf"><span>*</span>预约时段段设置</div>
      <div class="top_rg">七天可约  <gh-icon class="icon" name="consult-rg"></gh-icon></div>
    </div>
        <!-- 弹出添加时段的弹窗 -->
    <div class="addSche">
      <van-popup class="popup"   v-model:show="show" @close="close" round closeable position="top">
          <h2>预约创建</h2>
          <van-field 
          v-model="user_account"
          label="用户手机号"
          placeholder="请输入用户手机号" label-width="120px"
          clickable required  autocomplete="off"></van-field>
          <van-field 
          v-model="consultant_account"
          label="咨询师手机号"
          placeholder="请输入咨询师手机号" label-width="120px"
          clickable required  autocomplete="off"></van-field>
        <van-field 
         v-model="dateTime"
         readonly
         label="日期"
         placeholder="点击选择日期时间" label-width="120px"
         @click="showPicker=true"
         clickable required  autocomplete="off"></van-field>
            <!-- 展示日期选择器   -->
            <van-popup v-model:show="showPicker" round position="bottom">
              <van-datetime-picker
                  v-model="selectedDay"
                  type="date"
                  title="请选择日期"
                  :min-date="minDate"
                  :max-date="maxDate"
                  @cancel="showPicker=false"
                  @confirm="onConfirm"
                  :format="dateFormat"
            />
          </van-popup> 
          <van-field  v-model="timeSlot"  readonly  placeholder="选择时间段" label-width="120px"  label="时间段"
           clickable required  autocomplete="off"  @click="showTimeSlotsPickerFn"  is-link>
          </van-field> 
          <van-popup v-model:show="showTimeSlotsPicker" round position="bottom">
              <van-picker
                title="请选择时间段"
                :columns="time_periods"
                @cancel="showTimeSlotsPicker = false"
                @confirm="onTimeSlotConfirm"
              />
            </van-popup>
        <van-button native-type="submit" @click="addTime" :loading="isRegistering" :disabled="isRegistering" block round type="primary">
          确定
        </van-button>
        </van-popup>
  </div>
    <!-- 咨询师列表 -->
  <div class="consultant-list">
    <van-list v-if="consultantInfo.length > 0">
        <div class="total_consultants">共有{{consultantInfo.length}}条符合条件记录</div>
        <van-cell v-for="item in consultantInfo" :key="item.id" class="item1-item">
            <div class="name"> <img :src="item.avatar" alt="">  {{ item.name }}<gh-icon class="icon" name="consult-saoma"></gh-icon> </div>
            <div class="status">状态：<span>使用中</span> <div class="detail" @click="todetail(item)">详情 ></div> </div>
            <div class="paiqi">排期：<span>7天可预约</span></div>
            <div class="account">联系方式：{{item.account}}</div>
        </van-cell>
      </van-list>
      <van-empty v-else description="暂无咨询师信息" />
    </div>
  </div>
</template>

<script setup>
import {ref,reactive,onBeforeMount,computed,onMounted,watch,onBeforeUnmount} from "vue"
import { Toast, Dialog } from 'vant'
import 'vant/es/toast/style'
import{useRouter,useRoute}from 'vue-router'
import {useUserStore}from '@/stores'
import{getconsultantInfoByaccount,updateConsultantInfo, gettimeperiods,getavailableTimeBydate,addAvailableTimeBycoun_id}from '@/services/consultant'
import {getDetailConsultantInfo,getavailableTime,getAvailableToday,getAvailableByTime,appointment} from '@/services/booking'
import {getConsultants,delConsultant,updateConsultant,getconsultant_idByaccount,createAppointment,getavailableTimeBydateandis_booked } from '@/services/admin'
import {getuseridByaccount} from '@/services/others'
const route =useRoute()
const router =useRouter();  
const store = useUserStore()
const value=ref()
//用户和咨询师手机号响应式变量
const user_account=ref('')
const consultant_account=ref('')
//确定按钮加载响应式变量
const isRegistering = ref(false);
//定义时间选择器信息
const minDate = new Date();
    const maxDate = new Date(new Date().getTime() + 6 * 24 * 60 * 60 * 1000); // 7天后的日期
    const dateFormat = 'yyyy-MM-dd';
const show = ref(false);
const showPicker=ref(false)
const showTimeSlotsPicker=ref(false)
const consultantInfo=ref([])
//选择日期响应式变量
const dateTime=ref('')
//预约时间段响应式变量
const timeSlot=ref('')
//时间选择器选择日期
const selectedDay=ref(null)
//时间段查询响应式变量
const time_periods=ref({})
//点击添加时间段查询可预约时间段
const showTimeSlotsPickerFn=async()=>{
    if(user_account.value==''){
      Toast('请先填写用户手机号')
      return
    }
    if(consultant_account.value==''){
      Toast('请先填写咨询师手机号')
      return
    }
    if(dateTime.value==''){
        Toast('请先选择日期')
        return
    }
    const userId=await getuseridByaccount(user_account.value)
    if(!userId.data){
      Toast('用户手机账号不存在或号码格式错误')
      return
    }
    const consultantId=await getconsultant_idByaccount (consultant_account.value)
    if(!consultantId.data){
        Toast('咨询师手机账号不存在或号码格式错误')
        return
    }
    const id =consultantId.data.id
    const res=await getavailableTimeBydateandis_booked(id,dateTime.value)
    if(res.data.length===0){
      Toast('暂无可预约时间')
      return
    }
    time_periods.value=res.data
    showTimeSlotsPicker.value=true
    
   }
   // 选中的日期
 const selectedDate = ref(null);
   //选择日期
  const onConfirm = (value) => {
        const date = new Date(value);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');  
        const formattedDate = `${year}-${month}-${day}`;
        dateTime.value=formattedDate
        timeSlot.value=''
        showPicker.value=false
    };
onMounted(async()=>{
    const res=await getConsultants()
    // console.log(res.data)
    consultantInfo.value=res.data
})

//添加咨询师空闲时间
const addBookilng_time=()=>{
     show.value=true
}
//取消添加时段
const close=()=>{
     user_account.value=''
     consultant_account.value=''
     dateTime.value=''
     timeSlot.value=''
     show.value=false
}
//选择预约的时间段
const onTimeSlotConfirm=(value)=>{
      timeSlot.value=value
      showTimeSlotsPicker.value=false
}
//确定添加空闲时间
const addTime=async()=>{
   if(user_account.value==''){
      Toast('请先填写用户手机号')
      return
    }
    if(consultant_account.value==''){
      Toast('请先填写咨询师手机号')
      return
    }
    if(dateTime.value==''){
       Toast('请先选择日期')
       return
    }
    if(timeSlot.value==''){
      Toast('请先选择时间段')
      return
    }
    isRegistering.value=true
    const userId=await getuseridByaccount(user_account.value)
    const user_id=userId.data.id
    const consultantId=await getconsultant_idByaccount (consultant_account.value)
    const coun_id =consultantId.data.id
    const formData=new FormData();
    formData.append('coun_id',coun_id)
    formData.append('user_id',user_id)
    formData.append('date',dateTime.value)
    formData.append('timeSlot',timeSlot.value)
    const res=await createAppointment(formData).then((response)=>{
      return response
    }).catch((error)=>{
     return error
    })
    if(res.status!==201){
   if(res.response.status==402){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
       }
    }  
    console.log(res)
    Toast.success('添加成功!')
    isRegistering.value=false
    show.value=false
    
    // 刷新当前页面
     location.reload();
}


//点击跳转到详情页
const todetail=(item)=>{
  router.push(`/detailConsultant/${item.id}`)
}

</script>

<style lang="scss" scoped>
.appoint-page{
    width: 100%;
    .head{
        display: flex;
        position: fixed;
        z-index: 999;
        justify-content: space-between;
        align-items: center;
        min-height: 30px;
        background-color: #fff;
         top:35px;
         padding: 0 10px;
         .search{
            flex: 1;
         }
         .add-btn{
            background-color: var(--gh-admin);
            color: #fff;
            font-size: 14px;
            font-family: '黑体';
            border-radius: 5px;
            height: 30px;
            width: 130px;
         }
     }
     .top-box{
        position: fixed;
        z-index: 99;
        top: 85px;
        width: 95%;
        height: 50px;
        padding: 0 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #FEF2CE;
        .top_lf{
            font-size: 17px;
            font-weight: bold;
            span{
                color: red;
                margin-right: 5px;
            }
        }
        .top_rg{
            font-size: 15px;
            font-weight: bold;
            color: var(--gh-price);
            .icon{
                position: relative;
                top: 3px;
            }
        }
    }
    .addSche{
        display: flex;
        text-align: center;
       justify-content: center;
       flex-direction: column;
       .van-popup{
           .van-field{
              font-family: '黑体';
              font-size: 16px;
              .memu{
                width: 300px;
                position: relative;
                .custom-dropdown-item{
                    /* position: absolute; */
                    /* top: 0; */
                    /* left: 0; */
                }
              }
                

          }
         h2{
            margin-bottom: 5px;
            margin-top: 10px;
            font-size: 18px;
            font-weight: 600;
            font-family: '宋体';
          }
        .van-button{
              width: 80%;
              left: 50%;
              margin-top: 10px;
              transform: translate(-50%);
              height: 40px;
              margin-bottom: 20px;
              font-size: 16px;
             }
         }
      }
   .consultant-list{
            margin-top: 135px;
            padding:0 5px;
             .total_consultants{
                text-align: center;
                padding: 5px 0;
                font-size: 10px;
                color: var(--gh-text3);
             }
             .van-cell{
                background-color: #fff;
                border:1px solid var(--gh-line) ;
                padding: 0;
                margin-top: 12px;
                .name{
                    display: flex;
                    background-color: #f5f5f5;
                    align-items: center;
                    padding: 0 20px;
                    width: 100%;
                    font-size: 14px;
                    font-weight: bold;
                    line-height: 40px;
                    height: 40px;
                    img{
                      margin-right: 20px;
                      display: block;
                      height: 40px;
                      width: 40px;
                      border-radius: 12px;
                    }
                    .icon{
                       position: absolute;
                       right: 30px;
                       font-size: 17px;
                    }
                }
                 .status{
                  padding: 0 20px;
                  display: flex;
                  font-size: 14px;
                  font-weight: bold;
                  margin-top: 10px;
                  span{
                    color: var(--gh-primary);
                  }
                  .detail{
                    position: absolute;
                    right: 30px;
                    font-weight: bold;
                  }
                 }
                 .paiqi{
                  padding: 0 20px;
                  margin-top: 10px;
                  font-weight: bold;
                  span{
                    font-family: '黑体';
                  }
                 }
                 .account{
                    margin-top: 10px;
                    padding: 0 20px 10px;
                    color: var(--gh-price);
                    font-size: 12px;
                    
                 }
                 .operate{
                   width: 100%;
                   display: flex;
                   justify-content: space-between;
                   align-items: center;
                .van-button{
                   height: 25px;
                   font-size: 10px;
                   background-color: #f5f5f5;
            }
           }
             }
        }
}

</style>
